const {
  baseUrl,
  CODE
} = require('./config/api.js')
App({
  onLaunch() {
    this.checkLogin()
  },
  wxUserInfo: {},
  checkLogin() {
    // 检查Session是否过期，过期进行登录获取openid
    wx.checkSession({
      success: () => {
        console.log('未过期')
        const userInfo = wx.getStorageSync('userInfo')
        if (!Object.keys(userInfo).length) {
          this.init()
          return
        }
        this.globalData.userInfo = userInfo
      },
      fail: () => {
        console.log('过期')
        this.init()
      }
    })
  },
  init() {
    this.getWxInfo(() => {
      this.login()
    })
  },
  getWxInfo(callback) {
    this.getCode().then(v => {
      console.log(JSON.stringify(v))
      this.wxUserInfo.code = v.code
      return this.getUserInfo()
    }).then(res => {
      callback()
    }).catch(e => {
      console.error(e)
      // 授权页面
      wx.redirectTo({
        url: '/pages/authorize/authorize',
        success: () => {
          this.loading(500)
        }
      })
    })
  },
  login() {
    wx.request({
      url: baseUrl + '/wechat/user/login?code=' + this.wxUserInfo.code,
      success: (data) => {
        // 登录成功跳转
        console.log(JSON.stringify(data))
        this.globalData.userInfo.id = data.data.userid
        wx.switchTab({
          url: '/pages/index/index',
          success: (res) => {
            
            this.loading(500)
          },
          fail: (error) => {
            console.log(error)
          }
        })
      },
      fail() {}
    })
  },

  getCode() {
    return new Promise((resolve, reject) => {
      wx.login({
        success: resolve,
        fail: reject
      })
    })
  },
  getSetting() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        fail: reject,
        success: resolve
      })
    })
  },
  getUserInfo() {
    return new Promise((resolve, reject) => {
      wx.getUserInfo({
        withCredentials: true,
        fail: reject,
        success: resolve
      })
    })
  },
  loading(time) {
    wx.showLoading({
      title: '页面加载中',
    })
    setTimeout(function() {
      wx.hideLoading()
    }, time)
  },
  globalData: {
    userInfo: {}
  }
})